<template>
  <view :="fv.rootProps" v-if="state.visible">
    <view :class="[variables.ns.e('bottom')]">
      <Progress :="fv.progressProps" :class="[variables.ns.e('progress')]" />
      <view :class="[variables.ns.e('copyright')]" v-if="showCopyright">
        <view>{{ t('components.load-page.statement') }}</view>
        <view>{{ t('components.load-page.filings') }}</view>
        <view>{{ t('components.load-page.provider') }}</view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { awaitSetTimeout } from '@/utils'
import { LoadPageNS, variables } from '.'
import { computed, onBeforeUnmount, onMounted, reactive } from 'vue'
import Progress from '@/components/progress/index.vue'
import type { ProgressNS } from '@/components'
import { localFile } from '@/utils/local-file'
import { t } from '@/locale'
import { Timer } from '@/utils/timer'
import { merge } from 'lodash'

defineOptions({
  name: LoadPageNS.name
})
const props = defineProps(LoadPageNS.props)
const emits = defineEmits(LoadPageNS.emits)
const config = {
  timer: new Timer('Interval'),
}
const state = reactive({
  progress: <Omit<ProgressNS.Props,
    keyof (LoadPageNS.Props['progress'] & {})>>{ total: 100 },
  visible: false,
  showTransition: false
})
const fv = computed(() => {
  const rootProps = {
    class: [
      variables.ns.b,
      variables.ns.s('transition', state.showTransition),
    ],
    style: {
      [variables.ns.getCssVarName('background')]: `url(${localFile.getImage('components/load-page')}) 0 center / cover`,
      [variables.ns.getCssVarName('transitionDuration')]: variables.transitionTime + 'ms',
      [variables.ns.getCssVarName('progressTransitionDuration')]: variables.progressTransitionTime + 'ms',
    }
  }
  const progressProps = merge(<ProgressNS.Props>{
    showPercentageText: true,
    striped: true,
    stripedFlow: true,
  }, state.progress)
  
  return {
    rootProps,
    progressProps
  }
})

async function startLoad() {
  state.progress.current = 0
  emits('start')
  state.visible = true
  config.timer.stop()
  config.timer.run(() => {
    const c = state.progress.current! + 1
    const max = state.progress.total! - 1
    state.progress.current = Math.min(max, c)
    if (++state.progress.current! >= state.progress.total!) return config.timer.stop()
  }, 50)
  try {
    await props.load()
    emits('success')
  } catch (error) {
    emits('fail', error)
  }

  config.timer.stop()
  state.progress.current = state.progress.total

  await awaitSetTimeout(variables.progressTransitionTime)

  state.showTransition = true

  await awaitSetTimeout(variables.transitionTime)

  state.visible = false
  state.showTransition = false
  emits('complete')
}

onMounted(() => {
  if (props.auto) {
    startLoad()
  }
})
onBeforeUnmount(config.timer.stop)
defineExpose({
  startLoad
})
</script>